﻿using BLL.Sys;
using DEL.Sys;
using IBLL.Sys;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;

// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace Web.Areas.Sys.Controllers
{
    [Authorize(Roles = "super")]
    public class UserController : SysController<User>
    {
        protected override void SetCurrentEntityService()
        {
            CurrentEntityService = BLLFactory.SetUserService() ;
        }

        public JsonResult GetUserByDepartment(int pageIndex, int departmentId)
        {
            var rowCount = 0;
            var totalPages = 0;
            var result = CurrentEntityService.GetPagedEntitysByLambdaAndSort(pageIndex, PageSize, out rowCount, out totalPages, o => o.DepartmentId == departmentId, OrderLambda, IsASC);
            return Json(new
            {
                rowCount = rowCount,
                pageCount = totalPages,
                rows = result,
            });
        }

        /// <summary>
        /// 根据用户Id获取用户信息以及其所属于的角色
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public JsonResult GetUserWithRoles(int userId)
        {
            var user = CurrentEntityService.GetEntityById(userId);
            IList<UserRole> _roles = new List<UserRole>();
            if (user != null)
            {
                IUserRoleService _service = BLLFactory.SetUserRoleService();
                _roles = _service.GetEntitysByLambda(o => o.UserId == user.Id).ToList();
            }
            return Json(new { user = user, roles = _roles });
        }
        
        [Authorize,HttpGet]
        public IActionResult ModifyPsw()
        {
            return View();
        }

        [Authorize,HttpPost]
        public IActionResult ModifyPsw(User item, string oldPsw)
        {
            try
            {                
                var getItemById = CurrentEntityService.GetEntityById(item.Id);
                if (getItemById.Password != oldPsw)
                {
                    return Json(new
                    {
                        Result = "Faild",
                        Message = "原密码错误"
                    });
                }
                getItemById.Password = item.Password;
                CurrentEntityService.ModifyEntityAsync(getItemById);

                //退出当前用户的登录，删除登录的cookie信息
                HttpContext.Authentication.SignOutAsync("MyCookieMiddlewareInstance");
                return Json(new { Result = "Success" });
            }
            catch (Exception ex)
            {
                return Json(new
                {
                    Result = "Faild",
                    Message = ex.Message
                });
            }
        }

    }
}
